package com.lych.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lych.autoconfig.template.HuanXinTemplate;
import com.lych.commons.utils.Constants;
import com.lych.dubbo.api.*;
import com.lych.model.domain.Announcement;
import com.lych.model.domain.User;
import com.lych.model.domain.UserInfo;
import com.lych.model.enums.CommentType;
import com.lych.model.mongo.Comment;
import com.lych.model.mongo.Friend;
import com.lych.model.vo.*;
import com.lych.server.exception.BusinessException;
import com.lych.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private AnnouncementsApi announcementsApi;

    /**
     * 根据环信id查询用户详细信息
     * @param huanxinId
     * @return
     */
    public UserInfoVo findUserInfoByHuanXin(String huanxinId) {
        //根据huanxinId查询user用户信息
        User user = userApi.findByHuanXinId(huanxinId);
        //根据userId查询用户详细信息
        UserInfo userInfo = userInfoApi.findById(user.getId());
        //构造返回对象
        UserInfoVo vo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo,vo);
        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;

    }

    /**
     * 添加好友
     * @param friendId
     */
    public void contacts(Long friendId) {
        //将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(),
                Constants.HX_USER_PREFIX + friendId);
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
        //如果注册成功，将好友关系保存到mongo
        friendApi.save(friendId,UserHolder.getUserId());
    }

    /**
     * 分页查询联系人列表
     * @param page
     * @param pagesize
     * @param keyword
     * @return
     */
    public PageResult findContacts(Integer page, Integer pagesize, String keyword) {
        //调用api查询当前用户的好友
        List<Friend> list = friendApi.findByUserId(UserHolder.getUserId(),page,pagesize);
        //得到好友的id
        List<Long> ids = CollUtil.getFieldValues(list, "friendId", Long.class);
        //根据id查询详细用户信息
        UserInfo info = new UserInfo();
        info.setNickname(keyword);
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(ids, info);
        //构造vo对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo = infoMap.get(friend.getFriendId());
            if (userInfo != null) {
                ContactVo vo = ContactVo.init(userInfo);
                vos.add(vo);
            }
        }

        return new PageResult(page,pagesize,0,vos);
    }

    /**
     * 点赞列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult likes(Integer page, Integer pagesize) {
        //获得当前用户id
        Long userId = UserHolder.getUserId();
        //调用api查询点赞信息
        Comment comment = new Comment();
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setPublishUserId(userId);
        List<Comment> list = commentApi.findLikes(comment,page,pagesize);
        //非空判断
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }
        //根据点赞的人的id查询详细信息
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> info = userInfoApi.findByIds(ids, null);
        //构造对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment1 : list) {
            UserInfo userInfo = info.get(comment1.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo,comment1);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0,vos);
    }

    /**
     * 评论列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult comments(Integer page, Integer pagesize) {
        //得到当前用户id
        Long userId = UserHolder.getUserId();
        //调用api查询评论详细信息
        Comment comment = new Comment();
        comment.setPublishUserId(userId);
        comment.setCommentType(CommentType.COMMENT.getType());
        List<Comment> list = commentApi.findComment(comment,page,pagesize);
        //非空判断
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }
        //查询评论人的id查询详细数据
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(ids, null);
        //构造对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment1 : list) {
            UserInfo userInfo = infoMap.get(comment1.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo,comment1);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0,vos);
    }

    /**
     * 喜欢列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult loves(Integer page, Integer pagesize) {
        //获得当前用户id、
        Long userId = UserHolder.getUserId();
        //调用api获得喜欢详细信息
        Comment comment = new Comment();
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setPublishUserId(userId);
        List<Comment> list = commentApi.findLoves(page,pagesize,comment);
        //非空判断
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }
        //拿到具体id，根据id查询详细信息
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(ids, null);
        //封装对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment1 : list) {
            UserInfo userInfo = infoMap.get(comment1.getUserId());
            if (userInfo != null){
                CommentVo vo = CommentVo.init(userInfo,comment1);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0,vos);
    }

    /**
     * 公告列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult announcements(Integer page, Integer pagesize) throws ParseException {
        //调用api查询公告
        Page<Announcement> list = announcementsApi.findAll(page,pagesize);

        //非空判断
        if (list == null) {
            return new PageResult();
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        for (Announcement record : list.getRecords()) {
            Date parse = simpleDateFormat.parse(record.getCreated());
            record.setCreated(simpleDateFormat.format(parse));
        }
        //返回
        return new PageResult(page,pagesize,0,list.getRecords());
    }
}
